/*
 * Copyright 2009 Armando Blancas
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package taskgraph.channels;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.StreamCorruptedException;

import taskgraph.Config;
import taskgraph.ports.ByteInputPort;
import taskgraph.ports.ByteOutputPort;


/**
 * A channel that transports bytes. 
 * 
 * @author Armando Blancas
 */
public class ByteChannel {
	
	private static final int DEFAULT_BUFFER_SIZE = Config.get().channelCapacity();
	
    private final int bufferSize;
	private final PipedOutputStream output;
    private final PipedInputStream input;
    private final ByteOutputPort outputPort;
    private final ByteInputPort inputPort;
    
    /**
     * Creates a channel with the default buffer size.
     */
    public ByteChannel() {
    	this(DEFAULT_BUFFER_SIZE);
    }
    
    /**
     * Creates a channel with the passed buffer size.
     * 
     * @param bufferSize The buffer capacity in bytes. 
     */
    public ByteChannel(final int bufferSize) {
        if (bufferSize <= 0) {
            throw new IllegalArgumentException("ByteChannel bufferSize <= 0");
         }
        
		try {
			this.bufferSize = bufferSize;
			output = new PipedOutputStream();
			input = new PipedInputStream(output, bufferSize);
			outputPort = new OutputPort();
			inputPort = new InputPort();
		} catch (IOException e) {
			throw new Error(e);
		}
    }
    
    /**
     * Gets a reference to the output port.
     * 
     * @return An output interface to this channel.
     */
    public ByteOutputPort getOutputPort() {
    	return outputPort;
    }
    
    /**
     * Gets a reference to the input port.
     * 
     * @return An input interface to this channel.
     */
    public ByteInputPort getInputPort() {
    	return inputPort;
    }

    /**
     * Gets a port for writing to this channel as a data stream.
     * 
     * @return An output port as a {@code DataOutput} interface.
     */
    public DataOutput asDataOutput() {
    	return new DataOutputStream(
    			   new BufferedOutputStream(output, bufferSize));
	}

    /**
     * Gets a port for reading from this channel as a data stream.
     * 
     * @return An input port as a {@code DataInput} interface.
     */
    public DataInput asDataInput() {
    	return new DataInputStream(
    			   new BufferedInputStream(input, bufferSize));
    }
    
    /**
     * Gets a port for writing to this channel as an Object stream.
     * Interface {@code ObjectOutput} extends {@code DataOutput}.
     * 
     * @return An output port as a {@code ObjectOutput} interface.
     * @throws StreamCorruptedException If the stream header is incorrect.
     * @throws IOException If an I/O error occurs while reading stream header.
     * @throws SecurityException If untrusted subclass illegally overrides
     *         security-sensitive methods.
     */
    public ObjectOutput asObjectOutput() throws IOException {
    	return new ObjectOutputStream(
    			   new BufferedOutputStream(output, bufferSize));
	}

    /**
     * Gets a port for reading from this channel as an Object stream.
     * Interface {@code ObjectInput} extends {@code DataInput}.
     * 
     * @return An input port as a {@code ObjectInput} interface.
     * @throws StreamCorruptedException If the stream header is incorrect.
     * @throws IOException If an I/O error occurs while reading stream header.
     * @throws SecurityException If untrusted subclass illegally overrides
     * 		   security-sensitive methods.
     */
    public ObjectInput asObjectInput() throws IOException {
    	return new ObjectInputStream(
    		       new BufferedInputStream(input, bufferSize));
    }

    /**
     * A private implementation of the byte output port. It has direct access
     * to this channel and the byte input port. Instances of this class are 
     * published through the ByteOutputPort interface. 
     */
    private class OutputPort implements ByteOutputPort {
    
		@Override
		public ByteOutputPort write(int b) throws IOException {
			output.write(b);
			return this;
		}
	
		@Override
		public ByteOutputPort write(byte[] b) throws IOException {
			output.write(b);
			return this;
		}
	
		@Override
		public ByteOutputPort write(byte[] b, int off, int len) 
		throws IOException {
			output.write(b, off, len);
			return this;
		}
	
		@Override
		public void close() {
			try {
				output.close();
			} catch (IOException e) {
				// best effort
			}
		}
	
    }

    /**
     * A private implementation of the byte input port. It has direct access
     * to this channel and the byte output port. Instances of this class are 
     * published through the ByteInputPort interface. 
     */
    private class InputPort implements ByteInputPort {
	
		@Override
		public byte read() throws IOException {
			int value = input.read();
			if (value == -1) {
				throw new EOFException("EOF on input port");
			}
			return (byte)(0xff & value);
		}
	
		@Override
		public int read(byte[] b) throws IOException {
			return input.read(b);
		}
	
		@Override
		public int read(byte[] b, int off, int len) throws IOException {
			return input.read(b, off, len);
		}
	
		@Override
		public int skipBytes(int n) throws IOException {
	    	if (n < 0)
	    		throw new IllegalArgumentException("n is negative");
	    	if (n == 0)
	    		return 0;
	    	int toSkip = Math.min(n, input.available());
	    	byte[] f = new byte[toSkip];
	    	return read(f);
		}
	
		@Override
		public void close() {
			try {
				input.close();
			} catch (IOException e) {
				// best effort
			}
		}
		
    }

}
